/*
 * Copyright (C) 2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package top.xbaistack.game;

import lombok.Getter;
import lombok.Setter;
import top.xbaistack.utils.Utils;
import top.xbaistack.utils.WebSocket;

import javax.websocket.Session;
import java.io.IOException;

/**
 * 游戏玩家对象
 *
 * @author xbaistack
 * @since 2025/03/25
 */
@Getter
@Setter
public class Player {
    /**
     * 玩家ID，由服务端生成，UUID
     */
    private String id;

    /**
     * 玩家的所属角色（黑子、白子）
     */
    private Role role;

    /**
     * 是否冻结，当玩家下完棋之后就属于冻结状态，必须等到对方下完方可解冻。
     */
    private boolean frozen;

    /**
     * 玩家是否在线，当 WebSocket 链接断开时就代表玩家下线了。
     */
    private boolean online;

    /**
     * 是否是赢家
     */
    private boolean winner;

    /**
     * WebSocket 连接，需要用此对象来给用户推送消息。
     */
    private Session session;

    public Player(Role role) {
        this.id = Utils.generatedId();
        this.role = role;
    }

    public void setSession(Session session) {
        this.session = session;
        this.online = true;
    }

    public void offline() {
        this.online = false;
    }

    public void sendMessage(Object data) {
        WebSocket.sendMessage(getSession(), data);
    }

    public void exit() {
        if (session != null) {
            try {
                session.close();
            } catch (IOException e) {
            }
        }
    }
}

